const express = require('express')
const router = express.Router()
const ExpirationService = require('../../services/expirationService')
const auth = require('../../middleware/auth')
const { query, validationResult } = require('express-validator')
const logger = require('../../utils/logger')

/**
 * 手动处理过期积分
 * POST /api/admin/expiration/process
 */
router.post('/process', auth, async (req, res) => {
  try {
    const beforeDate = req.body.beforeDate ? new Date(req.body.beforeDate) : new Date()
    
    const result = await ExpirationService.processExpiredPoints(beforeDate)
    
    res.json({
      success: true,
      code: 200,
      message: '过期积分处理完成',
      data: result
    })
  } catch (error) {
    logger.error('手动处理过期积分失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '处理过期积分失败'
    })
  }
})

/**
 * 获取即将过期的积分
 * GET /api/admin/expiration/expiring
 */
router.get('/expiring', [
  auth,
  query('days').optional().isInt({ min: 1, max: 365 }).withMessage('天数必须在1-365之间')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const days = parseInt(req.query.days) || 7
    const expiringData = await ExpirationService.getExpiringPoints(null, days)
    
    res.json({
      success: true,
      code: 200,
      message: '获取即将过期积分成功',
      data: {
        days: days,
        users: expiringData
      }
    })
  } catch (error) {
    logger.error('获取即将过期积分失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '获取即将过期积分失败'
    })
  }
})

/**
 * 发送过期提醒通知
 * POST /api/admin/expiration/send-reminders
 */
router.post('/send-reminders', [
  auth,
  query('days').optional().isInt({ min: 1, max: 365 }).withMessage('天数必须在1-365之间')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const days = parseInt(req.query.days) || 7
    const expiringData = await ExpirationService.getExpiringPoints(null, days)
    
    if (expiringData.length === 0) {
      return res.json({
        success: true,
        code: 200,
        message: '没有需要提醒的即将过期积分',
        data: { sentCount: 0 }
      })
    }

    const result = await ExpirationService.sendExpirationNotifications(expiringData)
    
    res.json({
      success: true,
      code: 200,
      message: '过期提醒发送完成',
      data: result
    })
  } catch (error) {
    logger.error('发送过期提醒失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '发送过期提醒失败'
    })
  }
})

/**
 * 获取积分过期统计报表
 * GET /api/admin/expiration/report
 */
router.get('/report', [
  auth,
  query('startDate').isISO8601().withMessage('开始日期格式无效'),
  query('endDate').isISO8601().withMessage('结束日期格式无效')
], async (req, res) => {
  try {
    // 验证参数
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      })
    }

    const startDate = new Date(req.query.startDate)
    const endDate = new Date(req.query.endDate)
    
    // 验证日期范围
    if (startDate >= endDate) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '开始日期必须早于结束日期'
      })
    }

    const report = await ExpirationService.getExpirationReport(startDate, endDate)
    
    res.json({
      success: true,
      code: 200,
      message: '获取积分过期报表成功',
      data: report
    })
  } catch (error) {
    logger.error('获取积分过期报表失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '获取积分过期报表失败'
    })
  }
})

/**
 * 执行定时积分过期清理
 * POST /api/admin/expiration/scheduled-cleanup
 */
router.post('/scheduled-cleanup', auth, async (req, res) => {
  try {
    const result = await ExpirationService.scheduledExpiredPointsCleanup()
    
    res.json({
      success: true,
      code: 200,
      message: '定时积分过期清理完成',
      data: result
    })
  } catch (error) {
    logger.error('定时积分过期清理失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '定时积分过期清理失败'
    })
  }
})

/**
 * 执行定时积分过期提醒
 * POST /api/admin/expiration/scheduled-reminder
 */
router.post('/scheduled-reminder', auth, async (req, res) => {
  try {
    const result = await ExpirationService.scheduledExpirationReminder()
    
    res.json({
      success: true,
      code: 200,
      message: '定时积分过期提醒完成',
      data: result
    })
  } catch (error) {
    logger.error('定时积分过期提醒失败:', error)
    res.status(500).json({
      success: false,
      code: 500,
      message: error.message || '定时积分过期提醒失败'
    })
  }
})

module.exports = router